package com.lxj.student_security.service;

import com.lxj.student_security.entity.Permission;
import com.lxj.student_security.entity.User;
import com.lxj.student_security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.selectOne(s);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<Permission> list = userService.getPermissionsByUserId(user.getId());
        HashSet<Permission> permissions = new HashSet<>(list);
        user.setAuthorities(permissions);//获取权限的
        System.out.println(user);
        return user;
    }
}
